// pages/payment/payment.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    selectedAddress: null,
    goodsList: [],
    loading: true,
    remark: '',
    totalAmount: 0,
    totalQuantity: 0,
    shippingFee: 0,
    orderData: null,
    orderId: null,
    orderNo: null
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    if (options.orderId) {
      // 根据订单ID加载订单信息
      this.loadOrderInfo(options.orderId)
    } else if (options.goods) {
      // 兼容旧的方式，从购物车页面传递过来的商品数据
      try {
        const goodsData = JSON.parse(decodeURIComponent(options.goods))
        this.setData({
          goodsList: goodsData,
          orderData: goodsData
        })
        this.calculateTotal()
      } catch (e) {
        this.loadGoodsFromStorage()
      }
    } else {
      this.loadGoodsFromStorage()
    }
    this.loadDefaultAddress()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    // 读取本地选中地址
    const selectedAddress = wx.getStorageSync('selectedAddress')
    if (selectedAddress) {
      this.setData({ selectedAddress })
      wx.removeStorageSync('selectedAddress')
    } else {
      this.loadDefaultAddress()
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },

  // 从本地存储加载商品数据
  loadGoodsFromStorage() {
    try {
      const cartItems = wx.getStorageSync('cart') || []
      const selectedItems = cartItems.filter(item => item.selected)
      
      if (selectedItems.length === 0) {
        wx.showToast({
          title: '没有选中的商品',
          icon: 'none'
        })
        setTimeout(() => {
          wx.navigateBack()
        }, 1500)
        return
      }
      
      this.setData({
        goodsList: selectedItems,
        orderData: selectedItems,
        loading: false
      })
      this.calculateTotal()
    } catch (err) {
      this.setData({ loading: false })
    }
  },

  // 加载默认地址
  loadDefaultAddress() {
    wx.cloud.callFunction({
      name: 'addAddress',
      data: { getList: true },
      success: res => {
        const addresses = res.result.addresses || []
        const defaultAddress = addresses.find(addr => addr.is_default) || addresses[0]
        
        if (defaultAddress) {
          this.setData({ selectedAddress: defaultAddress })
        }
      }
    })
  },

  // 选择地址
  onSelectAddress() {
    wx.navigateTo({
      url: '/pages/address/address?select=true'
    })
  },

  // 备注输入
  onRemarkInput(e) {
    this.setData({
      remark: e.detail.value
    })
  },

  // 计算总价和运费
  calculateTotal() {
    const { goodsList } = this.data
    let totalAmount = 0
    let totalQuantity = 0
    
    goodsList.forEach(item => {
      totalAmount += item.price * item.num
      totalQuantity += item.num
    })
    
    // 计算运费（满99包邮）
    const shippingFee = totalAmount >= 99 ? 0 : 10
    
    this.setData({
      totalAmount: totalAmount + shippingFee,
      totalQuantity,
      shippingFee
    })
  },

  // 提交订单
  onSubmitOrder() {
    const { selectedAddress, remark, orderId, totalAmount } = this.data
    // 校验必填信息
    if (!selectedAddress) {
      wx.showToast({
        title: '请选择收货地址',
        icon: 'none'
      })
      return
    }
    
    if (!orderId) {
      wx.showToast({
        title: '订单信息错误',
        icon: 'none'
      })
      return
    }
    
    wx.showLoading({
      title: '提交订单中...'
    })
    
    // 先更新订单信息（地址和备注）
    wx.cloud.callFunction({
      name: 'updateOrder',
      data: {
        orderId: orderId,
        address: selectedAddress,
        remark: remark
      },
      success: res => {
        if (res.result.success) {
          // 更新成功后，创建支付
          this.createPayment()
        } else {
            console.log(res)
          wx.hideLoading()
          wx.showToast({
            title: res.result.message || '更新订单失败',
            icon: 'none'
          })
        }
      },
      fail: err => {
        wx.hideLoading()
        console.error('更新订单失败：', err)
        wx.showToast({
          title: '网络错误，请重试',
          icon: 'none'
        })
      }
    })
  },

  // 创建支付
  createPayment() {
    const { orderId, totalAmount } = this.data
    
    wx.cloud.callFunction({
      name: 'createPayment',
      data: {
        orderId: orderId,
        totalAmount: totalAmount
      },
      success: res => {
        wx.hideLoading()
        console.log(res)
        if (res.result.success) {
          // 调起微信支付
          this.requestPayment(res.result.paymentParams)
        } else {
          wx.showToast({
            title: res.result.message || '创建支付失败',
            icon: 'none'
          })
        }
      },
      fail: err => {
        wx.hideLoading()
        console.error('创建支付失败：', err)
        wx.showToast({
          title: '网络错误，请重试',
          icon: 'none'
        })
      }
    })
  },

  // 调起微信支付
  requestPayment(paymentParams) {
    wx.requestPayment({
      timeStamp: paymentParams.timeStamp,
      nonceStr: paymentParams.nonceStr,
      package: paymentParams.package,
      signType: paymentParams.signType,
      paySign: paymentParams.paySign,
      success: res => {
        console.log('支付成功：', res)
        this.handlePaymentSuccess()
      },
      fail: err => {
        console.log('支付失败：', err)
        this.handlePaymentFail(err)
      }
    })
  },

  // 处理支付成功
  handlePaymentSuccess() {
    wx.showToast({
      title: '支付成功',
      icon: 'success'
    })
    
    // 清除已购买的商品
    this.clearPurchasedItems()
    
    // 跳转到支付成功页面
    setTimeout(() => {
      wx.redirectTo({
        url: `/pages/payment-success/payment-success?orderId=${this.data.orderId}`
      })
    }, 1500)
  },

  // 处理支付失败
  handlePaymentFail(err) {
    let message = '支付失败'
    
    // 根据错误码显示具体原因
    if (err.errMsg) {
      if (err.errMsg.includes('cancel')) {
        message = '支付已取消'
      } else if (err.errMsg.includes('fail')) {
        message = '支付失败，请重试'
      } else if (err.errMsg.includes('timeout')) {
        message = '支付超时，请重试'
      }
    }
    
    wx.showModal({
      title: '支付失败',
      content: message,
      confirmText: '重试',
      cancelText: '返回',
      success: res => {
        if (res.confirm) {
          // 重试支付
          this.retryPayment()
        } else {
          // 返回订单页面
          wx.navigateBack()
        }
      }
    })
  },

  // 重试支付
  retryPayment() {
    // 先查询订单状态
    this.queryOrderStatus()
  },

  // 查询订单状态
  queryOrderStatus() {
    const { orderId } = this.data
    
    wx.showLoading({
      title: '查询订单状态...'
    })
    
    wx.cloud.callFunction({
      name: 'queryOrderStatus',
      data: { orderId: orderId },
      success: res => {
        wx.hideLoading()
        
        if (res.result.success) {
          if (res.result.payment_status === 'paid') {
            // 支付成功
            this.handlePaymentSuccess()
          } else if (res.result.payment_status === 'failed') {
            // 支付失败，重新创建支付
            this.createPayment()
          } else {
            // 其他状态，重新创建支付
            this.createPayment()
          }
        } else {
          wx.showToast({
            title: res.result.message || '查询失败',
            icon: 'none'
          })
        }
      },
      fail: err => {
        wx.hideLoading()
        console.error('查询订单状态失败：', err)
        wx.showToast({
          title: '网络错误，请重试',
          icon: 'none'
        })
      }
    })
  },

  // 清除已购买的商品
  clearPurchasedItems() {
    try {
      const cartItems = wx.getStorageSync('cart') || []
      const purchasedIds = this.data.goodsList.map(item => item.goods_id)
      const remainingItems = cartItems.filter(item => !purchasedIds.includes(item.goods_id))
      wx.setStorageSync('cart', remainingItems)
    } catch (err) {
      console.error('清除购物车失败：', err)
    }
  },

  // 根据订单ID加载订单信息
  loadOrderInfo(orderId) {
    wx.showLoading({
      title: '加载订单信息...'
    })
    
    wx.cloud.callFunction({
      name: 'getOrder',
      data: { orderId: orderId },
      success: res => {
        wx.hideLoading()
        
        if (res.result.success) {
          const orderInfo = res.result.order
          this.setData({
            goodsList: orderInfo.items,
            orderData: orderInfo,
            totalAmount: orderInfo.amount,
            shippingFee: orderInfo.shipping_fee,
            remark: orderInfo.remark || '',
            orderId: orderId,
            orderNo: orderInfo.order_no,
            loading: false
          })
          
          // 计算商品总数
          const totalQuantity = orderInfo.items.reduce((sum, item) => {
            return sum + item.num
          }, 0)
          
          this.setData({
            totalQuantity: totalQuantity
          })
        } else {
          wx.showToast({
            title: res.result.message || '加载订单失败',
            icon: 'none'
          })
        }
      },
      fail: err => {
        wx.hideLoading()
        console.error('加载订单失败：', err)
        wx.showToast({
          title: '网络错误，请重试',
          icon: 'none'
        })
      }
    })
  },

  onCancelOrder() {
    const { orderId } = this.data
    if (!orderId) {
      wx.showToast({ title: '订单信息错误', icon: 'none' })
      return
    }
    wx.showModal({
      title: '取消订单',
      content: '确定要取消并删除该订单吗？',
      confirmText: '确定',
      cancelText: '再想想',
      success: res => {
        if (res.confirm) {
          wx.showLoading({ title: '正在取消...' })
          wx.cloud.callFunction({
            name: 'deleteOrder',
            data: { orderId },
            success: res => {
              wx.hideLoading()
              if (res.result.success) {
                wx.showToast({ title: '订单已取消', icon: 'success' })
                setTimeout(() => {
                  wx.navigateBack()
                }, 1200)
              } else {
                wx.showToast({ title: res.result.message || '取消失败', icon: 'none' })
              }
            },
            fail: err => {
              wx.hideLoading()
              wx.showToast({ title: '网络错误，请重试', icon: 'none' })
            }
          })
        }
      }
    })
  },
})